package cn.psh.basic.service.impl;

import cn.psh.basic.dto.EamilRegisterDto;
import cn.psh.basic.dto.RegisterDto;
import cn.psh.basic.service.IVerifyCodeService;
import cn.psh.basic.util.StrUtils;
import cn.psh.basic.util.VerifyCodeUtils;
import cn.psh.basic.util.exception.BusinessException;
import cn.psh.user.domain.User;
import cn.psh.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;


@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;


    /**
     * 获取图形验证码
     *
     * @param key
     * @return
     */
    @Override
    public String getImgCode(String key) {
//        对key进行空值判断
        if (!StringUtils.hasLength(key)) {
            throw new BusinessException("空的   不得行");
        }
//        产生验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
//        存到redis  有效时间5分钟
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
//        把验证码转换为图片
//        使用base64编码转换为字符串返回给前端
        String imgcode = VerifyCodeUtils.verifyCode(115, 40, code);
        return imgcode;
    }

    /**
     * 获取手机短信
     *
     * @param smsCodeDto
     */
    @Override
    public void phoneCode(RegisterDto smsCodeDto) {
        //空值校验
        String phone = smsCodeDto.getPhone();
        String imageCode = smsCodeDto.getImageCode();
        String imageCodeKey = smsCodeDto.getImageKey();
        if(StringUtils.isEmpty(phone)){
            throw new  BusinessException("手机号不能为空！！");
        }
        if(StringUtils.isEmpty(imageCode)||StringUtils.isEmpty(imageCodeKey)){
            throw new BusinessException("信息不能为空");
        }

//        手机号是否被注册
         User user =  userMapper.queryByPhone(phone);
        if(user!=null){
            throw  new BusinessException("手机号已被注册，请直接登录");
        }
        //3.校验 - 图片验证码校验
        //3.1.图片验证码是否过期
        Object imageCodeValue = redisTemplate.opsForValue().get(imageCodeKey);
        if(imageCodeValue == null){
            throw new BusinessException("图形验证失效，重新获取！");
        }
        if(!imageCodeValue.toString().equalsIgnoreCase(imageCode)){
            throw new BusinessException("错误的图片验证码，请重新输入");
        }

//        查询redis存储的验证码
        Object phoneCode = redisTemplate.opsForValue().get("register" + phone);
        String code = "";
        if(phoneCode!=null) {
//            判断获取验证码时间是否过了60s（时间戳）
            Long oldTime = Long.valueOf(String.valueOf(imageCode.toString().split(":")[1]));
//            System.currentTimeMillis()===》现在的时间戳
            if (System.currentTimeMillis() - oldTime <= 1 * 60 * 1000) {
                throw new BusinessException("操作频繁，稍后重试!!!");
            } else {
                code = phoneCode.toString().split(":")[0];
            }
        }else {
            code = StrUtils.getComplexRandomString(4);
        }
        String codeTmp = code + ":" + System.currentTimeMillis();
        String registerPhone = "register:" + phone;
        redisTemplate.opsForValue().set(registerPhone,codeTmp,3,TimeUnit.MINUTES);

//        SmsUtils.sendSmsMsg(phone, "你的手机验证码为:"+code+"请在3分钟之内使用！！");
        System.out.println("你的手机验证码为:"+code+",请在3分钟之内使用！！");
    }

    @Override
    public void emailCode(EamilRegisterDto eamilRegisterDto) {
//        空校验
        final String email = eamilRegisterDto.getEmail();
        final String emailCode = eamilRegisterDto.getEmailCode();
        final String password = eamilRegisterDto.getEmailPassword();
        final String confirmPassword = eamilRegisterDto.getEmailConfirmPassword();
        if(email ==null ||emailCode == null || password == null ||confirmPassword == null){
            throw new BusinessException("信息不能为空");
        }
//        查询redis存储的验证码
        Object phoneCode = redisTemplate.opsForValue().get("register" + email);
        String code = "";
        if(phoneCode == null) {
            code = StrUtils.getComplexRandomString(4);
        }else {
            code = phoneCode.toString().split(":")[0];
        }
        String codeTmp = code + ":" + System.currentTimeMillis();
        String registerPhone = "register:" + email;
        redisTemplate.opsForValue().set(registerPhone,codeTmp,3,TimeUnit.MINUTES);
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //设置发送人
        mailMessage.setFrom("2291748032@qq.com");
        //邮件主题
        mailMessage.setSubject("宠物乐园");
        //邮件内容
        mailMessage.setText("你的邮箱验证码为:"+code+",请在3分钟之内使用！！");
        //收件人
        mailMessage.setTo("3559306627@qq.com");

        javaMailSender.send(mailMessage);



        System.out.println("你的手机验证码为:"+code+",请在3分钟之内使用！！");
    }

    /**
     * 绑定手机
     * @param smsCodeDto
     */
    @Override
    public void binderSmsCode(RegisterDto smsCodeDto) {

        //空值校验
        String phone = smsCodeDto.getPhone();
        if(StringUtils.isEmpty(phone)){
            throw new  BusinessException("手机号不能为空！！");
        }
//        手机号是否被注册
        User user =  userMapper.queryByPhone(phone);
        if(user!=null){
            throw  new BusinessException("手机号已被注册，请直接登录");
        }
        //3.校验 - 图片验证码校验
        //3.1.图片验证码是否过期

//        查询redis存储的验证码
        Object phoneCode = redisTemplate.opsForValue().get("binder" + phone);
        String code = "";
        if(phoneCode!=null) {
                code = phoneCode.toString().split(":")[0];
        }else {
            code = StrUtils.getComplexRandomString(4);
        }
        String codeTmp = code + ":" + System.currentTimeMillis();
        String registerPhone = "binder:" + phone;
        redisTemplate.opsForValue().set(registerPhone,codeTmp,3,TimeUnit.MINUTES);

//        SmsUtils.sendSmsMsg(phone, "你的手机验证码为:"+code+"请在3分钟之内使用！！");
        System.out.println("你的手机验证码为:"+code+",请在3分钟之内使用！！");
    }


}
